Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

592
Vistas
"Type 'null' cannot be used as an index type" TS

I receive an error in Typescript code when I use my "language" const: "Type 'null' cannot be used as an index type."

const language =
      localStorage.getItem("language") !== null
        ? localStorage.getItem("language")
        : "en"; 
     
someText = someArray[language];

How can I fix it and why isn't working when I prevent language const from being null? (I know that index selector must by string/number)

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

The problem here (and the reason why TypeScript cannot infer the correct type of language) is that localStorage.getItem("language") is being evaluated two times, and it could as well - for what the compiler knows - return null upon the second invocation.

Use the ?? operator to exclude the possibility of language being null.

const language = localStorage.getItem("language") ?? "en"; 
someText = someArray[language];
over 4 years ago · Santiago Trujillo Denunciar

0

You can just tweak your code a bit using Nullish Coalescing operator (??), which is basically what is share by GOTO. Just explaining it's name & working.

let someText = someArray[(localStorage.getItem("language") ?? "en")]

From MDN docs, The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda